package com.gw.yunke.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gw.yunke.constant.GlobalConstant;
import com.gw.yunke.domain.User;
import com.gw.yunke.domain.dto.DataObj;
import com.gw.yunke.domain.dto.ResultData;
import com.gw.yunke.domain.dto.UserReq;
import com.gw.yunke.domain.dto.UserSimpleInfo;
import com.gw.yunke.domain.dto.UserToken;
import com.gw.yunke.exception.ErrorInfo;
import com.gw.yunke.service.IInstituteService;
import com.gw.yunke.service.IUserService;
import com.gw.yunke.service.impl.MultipartFileService;
import com.gw.yunke.utils.EncryptUtils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static com.gw.yunke.domain.dto.ResultData.ERROR;
import static com.gw.yunke.domain.dto.ResultData.OK;

/**
 * 处理用户登录注册请求
 */

@RestController
public class UserController {

  @Autowired
  private IUserService userService;
  @Autowired
  private GlobalConstant constant;
  @Autowired
  private MultipartFileService multipartFileService;
  @Autowired
  private IInstituteService instituteService;

  public Object login(UserReq userReq) {

    return null;
  }

  @RequestMapping(value = "/register", method = RequestMethod.POST)
  public Object register(@RequestParam(value = "email", required = true) String email,
                         @RequestParam(value = "password", required = true) String password,
                         @RequestParam(value = "name", required = true) String name,
                         HttpServletResponse response) {
    User user = new User();
    user.setEmail(email);
    user.setName(name);
    user.setPassword(password);

    ResultData<String> resultData = new ResultData<>();

    UserReq req = new UserReq();
    req.setEmail(email);
    req.setName(name);
    List<User> users = userService.getUserByExample(req);
    if (users.size() > 0) {
      resultData.setCode(ResultData.ERROR);
      resultData.setData("用户名或密码重复");
      resultData.setMessage("fail");
      return resultData;
    }


    int result = userService.saveUser(user);

    if (result > 0) {
      Cookie cookie = new Cookie("sso", email);
      cookie.setMaxAge(60 * 60 * 6);
      response.addCookie(cookie);
      resultData.setCode(OK);
      resultData.setData("ok");
      resultData.setMessage("succeed");
    } else {
      resultData.setCode(ResultData.ERROR);
      resultData.setData("注册失败");
      resultData.setMessage("fail");
    }
    return resultData;
  }

  @RequestMapping(value = "/check", method = RequestMethod.GET)
  public Object checkName(UserReq req) {
    List<User> users = userService.getUserByExample(req);
    ResultData<String> resultData = new ResultData<>();
    if (!StringUtils.isEmpty(req.getEmail()) && users.size() > 0) {
      resultData.setCode(ResultData.ERROR);
      resultData.setData("邮箱已被注册");
      resultData.setMessage("");
    } else if (!StringUtils.isEmpty(req.getName()) && users.size() > 0) {
      resultData.setCode(ResultData.ERROR);
      resultData.setData("用户名已被注册");
      resultData.setMessage("");
    } else {
      resultData.setCode(OK);
      resultData.setData("ok");
      resultData.setMessage("succeed");
    }
    return resultData;
  }

  @RequestMapping(value = "/login", method = RequestMethod.POST)
  public ResultData login(@RequestBody UserReq userReq, HttpServletRequest request,
                          HttpServletResponse response) throws JsonProcessingException {
    System.out.println("login");
    ResultData resultData = new ResultData();
    if (userReq == null || StringUtils.isEmpty(userReq.getEmail())) {
      resultData.setCode(ResultData.ERROR);
      resultData.setData(-1);
      resultData.setMessage("参数错误");
      return resultData;
    }
    List<User> userList = userService.getUserByExample(userReq);

    if (userList.size() <= 0 || !userList.get(0).getPassword().equals(userReq.getPassword())) {
      resultData.setCode(OK);
      resultData.setData(-1);
      resultData.setMessage("邮箱或密码错误");
    } else {

      UserToken userToken = buildUserToken(userList.get(0));

      if (userReq.getKeepLogin() != null) {
        userToken.setEndTime(new Date().getTime() + 1000 * 60 * 60 * 24 * 7);
      } else {
        userToken.setEndTime(new Date().getTime() + 1000 * 60 * 60 * 5);
      }
      String jsonString = new ObjectMapper().writeValueAsString(userToken);
      String token = EncryptUtils.sha256HMACEncode(jsonString, "yunke");
      System.out.println("*************token=" + token);
      Cookie cookie = new Cookie("sso", token);
      cookie.setDomain(constant.getDomainWithoutPort());
      cookie.setPath("/");
      cookie.setHttpOnly(true);
      //cookie.setMaxAge(60*60*6);
      if (userReq.getKeepLogin() != null && userReq.getKeepLogin() > 0) {
        cookie.setMaxAge(60 * 60 * 24 * 7);
      }

      UserSimpleInfo userSimpleInfo = userService.buildUserSimpleInfo(userList.get(0));

      DataObj<UserSimpleInfo> dataObj = new DataObj<>();
      dataObj.setUserInfo(userSimpleInfo);
      dataObj.setState(1);

      response.addCookie(cookie);
      resultData.setCode(OK);
      resultData.setData(dataObj);
      resultData.setMessage("登录成功");
    }
    return resultData;
  }

  private UserToken buildUserToken(User user) {
    UserToken userToken = new UserToken();
    BeanUtils.copyProperties(user, userToken);
    return userToken;
  }

  @RequestMapping(value = "/getUserSimpleInfo", method = RequestMethod.POST)
  public ResultData<UserSimpleInfo> getUserInfo(@CookieValue("sso") String token) throws Exception {
    User user = new User();
    ResultData<UserSimpleInfo> resultData = new ResultData<>();
    try {
      int result = userService.checkLogin(token, user);
      if (result < 0) {
        resultData.setCode(ERROR);
        resultData.setMessage("登录信息错误");
        return resultData;
      }
      UserSimpleInfo userSimpleInfo = userService.buildUserSimpleInfo(user);
      resultData.setData(userSimpleInfo);
      resultData.setCode(OK);
      return resultData;
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
  }

  @RequestMapping(value = "/mockLogin", method = RequestMethod.GET)
  public void mockLogin(HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException {
    User user = userService.getUserById(3L);
    ObjectMapper objectMapper = new ObjectMapper();
    String s = objectMapper.writeValueAsString(user);
    Cookie cookie = new Cookie("sso", EncryptUtils.sha256HMACEncode(s, "yunke"));
    //cookie.setMaxAge(60*60);
    cookie.setDomain("192.168.3.2");
    cookie.setPath("/");

    //request.getSession().getServletContext().
    response.addCookie(cookie);

  }

  @RequestMapping(value = "/logout", method = RequestMethod.POST)
  public ResultData logout(@CookieValue(value = "sso", required = false) String token, HttpServletResponse response) {
    ResultData resultData = new ResultData();
    if (StringUtils.isEmpty(token)) {
      resultData.setCode(OK);
      resultData.setData(-1);
      resultData.setMessage("还未登录");
    } else {
      Cookie cookie = new Cookie("sso", "");
      cookie.setDomain(constant.getDomainWithoutPort());
      cookie.setPath("/");
      cookie.setMaxAge(0);
      response.addCookie(cookie);
      resultData.setCode(OK);
      resultData.setData(1);
    }
    return resultData;
  }

  @RequestMapping(value = "/checkLogin", method = RequestMethod.POST)
  public ResultData checkLogin(@CookieValue(value = "sso", required = false) String token) {

    ResultData resultData = new ResultData();
    resultData.setCode(OK);
    if (StringUtils.isEmpty(token)) {
      resultData.setData(-1);
    }
    try {
      User user = userService.getUserInfoByToken(token);
      if (user != null) {
        UserSimpleInfo userSimpleInfo = userService.buildUserSimpleInfo(user);

        DataObj<UserSimpleInfo> dataObj = new DataObj<>();
        dataObj.setUserInfo(userSimpleInfo);
        dataObj.setState(1);

        resultData.setData(dataObj);
      } else {
        resultData.setData(-1);
      }

    } catch (Exception e) {
      resultData.setData(-1);
    }
    return resultData;
  }

  @RequestMapping(value = "/updateImage", method = RequestMethod.POST)
  public ResultData addHeadImage(@RequestParam("file") MultipartFile multipartFile, @CookieValue("sso") String token) throws Exception {

    ResultData resultData = new ResultData();
    resultData.setCode(OK);
    User user = new User();
    int result = userService.checkLogin(token, user);
    if (result == -1) {
      resultData.setData(-1);
      resultData.setMessage("没有获取到登录信息,请重新登录");
      return resultData;
    }
    Long imageId = multipartFileService.upLoadImage(multipartFile);
    user.setImageId(imageId);
    userService.updateUser(user);
    resultData.setData(0);
    resultData.setMessage("添加成功");
    return resultData;
  }

  @RequestMapping(value = "/teacherLogin", method = RequestMethod.POST)
  public ResultData teacherLogin(@RequestBody UserReq userReq, HttpServletRequest request,
                                 HttpServletResponse response) throws JsonProcessingException {

    System.out.println("login");
    ResultData resultData = new ResultData();
    if (userReq == null || StringUtils.isEmpty(userReq.getEmail())) {
      resultData.setCode(ResultData.ERROR);
      resultData.setData(-1);
      resultData.setMessage("参数错误");
      return resultData;
    }
    List<User> userList = userService.getUserByExample(userReq);

    if (userList.size() <= 0 || !userList.get(0).getPassword().equals(userReq.getPassword())) {
      resultData.setCode(OK);
      resultData.setData(-1);
      resultData.setMessage("邮箱或密码错误");
      return resultData;
    } else {
      if(!userList.get(0).getType()){
        resultData.setCode(OK);
        resultData.setData(-1);
        resultData.setMessage("账号非教师");
        return resultData;
      }
      UserToken userToken = buildUserToken(userList.get(0));

      if (userReq.getKeepLogin() != null) {
        userToken.setEndTime(new Date().getTime() + 1000 * 60 * 60 * 24 * 7);
      } else {
        userToken.setEndTime(new Date().getTime() + 1000 * 60 * 60 * 5);
      }
      String jsonString = new ObjectMapper().writeValueAsString(userToken);
      String token = EncryptUtils.sha256HMACEncode(jsonString, "yunke");
      System.out.println("*************token=" + token);
      Cookie cookie = new Cookie("sso", token);
      cookie.setDomain(constant.getDomainWithoutPort());
      cookie.setPath("/");
      cookie.setHttpOnly(true);
      //cookie.setMaxAge(60*60*6);
      if (userReq.getKeepLogin() != null && userReq.getKeepLogin() > 0) {
        cookie.setMaxAge(60 * 60 * 24 * 7);
      }

      UserSimpleInfo userSimpleInfo = userService.buildUserSimpleInfo(userList.get(0));

      DataObj<UserSimpleInfo> dataObj = new DataObj<>();
      dataObj.setUserInfo(userSimpleInfo);
      dataObj.setState(1);

      response.addCookie(cookie);
      resultData.setCode(OK);
      resultData.setData(dataObj);
      resultData.setMessage("登录成功");
    }
    return resultData;
  }
}
